<?php

include_once 'classes/DBCon.php';
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Forum
 *
 * @author Moofie
 */
class Forum {

    private $con;
    private $fid;
    private $forumtitle;
    private $description;
    private $threads;
    private $posts;
    private $status;
    private $selectForum = 'SELECT fid,forumtitle,description,threads,posts FROM forum;';
    private $selectThread = 'SELECT * FROM thread WHERE fid=? AND status="Available" ORDER BY timestamp(threadDate, threadTime) DESC;';
    private $selectThreadStarterPost = 'SELECT u.username,u.groupId,u.registerDate, u.uid, u.postCount, message, threadDate, threadTime, title, fid FROM users u, thread t WHERE t.uid=u.uid AND t.tid =?;';
    private $selectAllPost = 'SELECT username,groupId,registerDate,postCount, pid, u.uid, title, message, timestamp(postDate, postTime) FROM post p, users u WHERE p.uid=u.uid AND p.tid=? AND status="Available" ORDER BY timestamp(postDate, postTime) ASC;';
    private $selectUserPostCount = 'SELECT COUNT(pid) FROM post p , users u WHERE p.status="Available" AND u.uid = p.uid AND u.uid=?;';
    private $selectTotalUsers = 'SELECT COUNT(uid) FROM users;';
    private $updatePostCount = 'UPDATE users SET postCount = ? WHERE uid=?;';
    private $selectTotalThread = 'SELECT COUNT(tid) FROM thread WHERE fid=?;';
    private $selectForumLatestPost = 'SELECT u.username, p.message, timestamp(p.postDate,p.postTime) FROM forum f, thread t, post p, users u  WHERE f.fid = t.fid AND t.tid = p.tid AND p.uid=u.uid AND f.fid=? ORDER BY timestamp(p.postDate,p.postTime) DESC LIMIT 1;';
    private $selectTotalPost = 'SELECT COUNT(pid) FROM forum f, thread t, post p WHERE f.fid = t.fid AND t.tid = p.tid AND f.fid=?;';
    private $selectThreadStarter = 'SELECT u.username FROM users u, thread t WHERE u.uid = t.uid AND t.tid =?;';
    private $selectThreadLatestPost = 'SELECT u.username,p.pid, p.message, timestamp(p.postDate, p.postTime) FROM users u, thread t, post p WHERE  t.tid = p.tid AND p.uid = u.uid AND t.tid =? ORDER BY timestamp(p.postDate, p.postTime) DESC LIMIT 1;';
    private $selectThreadLatestPostFromThread = 'SELECT u.username,t.tid, t.message, timestamp(t.threadDate, t.threadTime) FROM users u, thread t, post p WHERE t.uid = u.uid AND t.tid =? ORDER BY timestamp(t.threadDate, t.threadTime) DESC LIMIT 1;';
    private $selectThreadTotalPost = 'SELECT COUNT(p.pid) FROM thread t, post p WHERE t.tid = p.tid AND t.tid = ?;';
    private $selectUserJoinedDate = 'SELECT registerDate FROM users WHERE uid=?;';
    private $selectNextPostId = 'SELECT pid FROM post ORDER BY timestamp(postDate, postTime) DESC LIMIT 1;';
    private $selectNextThreadId = 'SELECT tid FROM thread ORDER BY timestamp(threadDate, threadTime) DESC LIMIT 1;';
    private $selectThreadCountId = 'SELECT COUNT(tid) FROM thread;';
    private $insertPost = 'INSERT INTO post(pid,tid,uid,title,message,postDate,postTime,status) VALUES (?,?,?,?,?,?,?,?);';
    private $insertThread = 'INSERT INTO thread(tid,fid,uid,title,message,threadDate,threadTime) VALUES (?,?,?,?,?,?,?);';
    private $selectCountPostId = 'SELECT COUNT(pid) FROM post;';
    private $selectForumTitle = 'SELECT f.forumtitle FROM Forum f, Thread t Where f.fid=t.fid AND f.fid=? LIMIT 1;';
    private $selectThreadTitleOnly = 'SELECT title FROM thread WHERE tid=?;';
    private $selectThreadTitle = 'SELECT f.forumtitle, f.fid, t.title FROM thread t, forum f WHERE f.fid=t.fid AND t.tid =?;';
    private $selectUserGrpId = 'SELECT groupId FROM users WHERE uid=?;';
    private $updateBanUser = 'UPDATE users SET groupId = 4 WHERE uid = ?;';
    private $updateUnBanUser = 'UPDATE users SET groupId = 3 WHERE uid = ?;';
    private $deletePost = 'UPDATE post SET status = "Deleted" WHERE pid = ?;';
    private $updatePost = 'UPDATE post SET message = ? WHERE pid = ?;';

    function __construct() {
        $this->con = DBCon::connectDB();
    }

    public function displayForumBoard() {
        $content = "";
        $content .='<div class="row"><fieldset>';
        $content .='<legend>Forum Board Discussion</legend>';
        $content .='<table border="1" width="" id="posts_list" align="center">';
        $content .='<tr>';
        $content .='<th><h4>Category</h4></th>';
        $content .='<th><h4>Description</h4></th>';
        $content .='<th><h4>Threads/Posts</h4></th>';
        $content .='<th><h4>Last Post</h4></th>';
        $content .='</tr>';

        $pstmtSelect = $this->con->prepare($this->selectForum);
        $pstmtSelect->execute();
        $pstmtSelect->bind_result($this->fid, $this->forumtitle, $this->description, $this->threads, $this->posts);
        $pstmtSelect->store_result();
        while ($pstmtSelect->fetch()) {
            $content .='<tr>';
            $content .= '<td class="title">';
            $content .= '<a href="view_thread.php?permalink=';
            $content .= htmlspecialchars($this->fid) . '">' . $this->forumtitle . '</a>';
            $content .= '</td>';
            $content .= '<td align="center">' . htmlspecialchars($this->description) . '</td>';
            $content .= '<td align="center">Threads:' . $this->getTotalThread($this->fid) . '<br />Posts:   ' . $this->getTotalPost($this->fid) . '</td>';
            $content .=$this->getForumLatestPost($this->fid);
            
            $content .='</tr>';
        }
        $content .='</table>';      
        $content .='</fieldset></div>';
        echo $content;
    }

    public function displayThreads($id) {
        $content = '';

        $pstmtSelect = $this->con->prepare($this->selectThread);
        $pstmtSelect->bind_param('s', $id);
        $pstmtSelect->execute();
        $pstmtSelect->bind_result($this->tid, $this->fid, $this->uid, $this->title, $this->message, $this->threadDate, $this->threadTime, $this->status);
        $pstmtSelect->store_result();
        $content .='<div class="row"><fieldset>';
        $content .='<legend>' . htmlspecialchars($this->getForumCategoryTitle($_REQUEST['permalink'])) . '</legend>';
        $content .='<legend>';
        $content .= $this->getCurrentForumPagePath($_REQUEST['permalink']);
        $content .='</legend>';
        $content .='<a href="newThread.php?threads='.htmlspecialchars($_REQUEST['permalink']).'"><img src="img/NewThreadButton.png"></a>';
        $content .='<table border="1" width="" id="posts_list" align="center">';
        $content .='<tr>';
        $content .='<th><h4>Title</h4></th>';
        $content .='<th><h4>Thread Starter</h4></th>';
        $content .='<th><h4>Last Post</h4></th>';
        $content .='<th><h4>Replies</h4></th>';
        if($_SESSION['groupId']==1){
            $content .='<th><h4>Delete?</h4></th>';
        }
        $content .='</tr>';
        $content .='<tr>';
        $content .='</tr>';

        while ($pstmtSelect->fetch()) {
            $content .='<tr>';
            $content .= '<td class="title">';
            $content .= '<a href="view_threads.php?permalink=';
            $content .= htmlspecialchars($this->tid) . '">' . $this->title . '</a>';
            $content .= '</td>';
            $content .=$this->getThreadStarterUsername($this->tid);
            if ($this->getThreadLastPostFromPost($this->tid) == 'NULL') {
                $content .= $this->getThreadLastPostFromThread($this->tid);
            } else {
                $content .= $this->getThreadLastPostFromPost($this->tid);
            }

            $content .='<td style="color:grey;text-align:center;">Total Replied: <b>' . $this->getTotalThreadPost($this->tid) . '</b></td>';
             if($_SESSION['groupId']==1){
                $content .='<td><a href="asdsad.php">Delete</a></td>';
             }   
            $content .='</tr>';
        }

        $content .='</table>';
        $content .='</fieldset></div>';
        echo $content;
    }

    public function viewThreads($tid) {
        $i = 0;
        $j = 0;
        $content = '';
        $content .='<fieldset>';
        $content .='<legend font-size="20px">' . htmlspecialchars($this->getForumThreadTitle($_REQUEST['permalink'])) . '';
        $content .='</legend>';
        $content .='<legend>';
        $content .= $this->getCurrentThreadPagePath($_REQUEST['permalink']);
        $content .='</legend>';
        $content .= '<div id="refreshPost" name="refreshPost">';
        $spost = array();
        $posts = null;
        $content .='<div class="alert alert-box" data-alert id="banErr" style="display: none"></div>';
        $content .= '<form id="addNewPost"><input type="hidden" name="action" value="addNewPost"/>';
        $content .='<div id="info">';
        $pstmtSelect = $this->con->prepare($this->selectThreadStarterPost);
        $pstmtSelect->bind_param('s', $tid);
        $pstmtSelect->bind_result($spost['username'], $spost['groupId'], $spost['registerDate'], $spost['uid'], $spost['postCount'], $spost['message'], $spost['threadDate'], $spost['threadTime'], $spost['title'], $spost['fid']);
        $pstmtSelect->execute();
        while ($pstmtSelect->fetch()) {
            foreach ($spost as $key => $value) {
                $row[$key] = $value;
            }
            $posts = $row;
            $content .='<table border="1" width="" id="posts_list" align="center" style="table-layout:fixed; width: 65%">';
            $content .='<tr>';
            $content .='<td>#0</td>';
            $content .='<td style="table-layout: fixed; width: 65%"><b>Title : </b>' . $row['title'] . '</td>';
            $content .='<td>' . $row['threadDate'] . '&nbsp ' . $row['threadTime'] . '</td>';
            $content .='</tr>';
            $content .='<tr>';
            $content .='<td width="150px">' . $row['username'] . '<br /><img src="css/images/forum_profile_pic.jpg" /><br />Date Joined :' . $row['registerDate'] . '<br />Post: ' . $row['postCount'] . '<br />';
            if ($row['groupId'] == 1) {
                $content .='Admin';
            } else if ($row['groupId'] == 2) {
                $content .='Moderator';
            } else if ($row['groupId'] == 3) {
                $content .='Member';
            } else if ($row['groupId'] == 4) {
                $content .='Banned';
            } else {
                $content .='Unknown';
            }

            if ($_SESSION['groupId'] == 1 || $_SESSION['groupId'] == 2) {
                if ($row['groupId'] == 3) {
                    ++$i;
                    $content .='<form id="banMember">';
                    //$content .='<input type="hidden" name="action" value="banUser"/>';
                    $content .='<br /><input type="button" id="ban' . $i . '" value="Ban" class="button left tiny" align="center" onclick=\'banUser("' . $row['uid'] . '");\'></input>'; 
                    $content .='</form>';
                } else if ($row['groupId'] == 4) {
                    ++$j;
                    $content .='<br /><input type="button" id="unban' . $j . '" value="unBan" class="button left tiny" align="center" onclick=\'unbanUser("' . $row['uid'] . '");\'></input>';
                }
            }
            if($_SESSION['uid']!=$row['uid']){
                $content .='<br /><a href="privatemessage.php?ruid='.$row['uid'].'" >Message</a>';
            }
            $content .='</td>';
            $content .='<td style="position:relative" width="750px" colspan="2">' . $row['message'] . '</td>';
            $content .='</tr>';
        }
        $content .='</table>';
        $pstmtSelect->close();

        $spost2 = array();
        $posts2 = null;
        $a = 0;
        $pstmtSelectPost = $this->con->prepare($this->selectAllPost);
        $pstmtSelectPost->bind_param('s', $tid);
        $pstmtSelectPost->bind_result($spost2['username'], $spost2['groupId'], $spost2['registerDate'], $spost2['postCount'], $spost2['pid'], $spost2['uid'], $spost2['title'], $spost2['message'], $spost2['postDateTime']);
        $pstmtSelectPost->execute();
        while ($pstmtSelectPost->fetch()) {
            foreach ($spost2 as $key => $value) {
                $row2[$key] = $value;
            }
            ++$a;
            $posts2 = $row2;
            $content .='<table class="table1" cellpadding="0" cellspacing="0" border="1" width="" id="posts_list" align="center" table-layout="fixed" width="350px" height="15px" style="table-layout: fixed; width: 65%">';
            $content .='<tr>';
            $content .='<td>#'.htmlspecialchars($a).'</td>';
            $content .='<td  style="table-layout: fixed; width: 65%"></td>';
            $content .='<td>' . $row2['postDateTime'] . '</td>';
            $content .='</tr>';
            $content .='<tr>';
            $content .='<td width="150px">' . $row2['username'] . '<br /><img src="css/images/forum_profile_pic.jpg" /><br />Date Joined :' . $row2['registerDate'] . '<br />Post:' . $row2['postCount'] . '<br />';
            if ($row2['groupId'] == 1) {
                $content .='Admin';
            } else if ($row2['groupId'] == 2) {
                $content .='Moderator';
            } else if ($row2['groupId'] == 3) {
                $content .='Member';
            } else if ($row2['groupId'] == 4) {
                $content .='Banned';
            } else {
                $content .='Unknown';
            }

            if ($_SESSION['groupId'] == 1 || $_SESSION['groupId'] == 2) {
                if ($row2['groupId'] == 3) {
                    ++$i;
                    $content .='<form id="banMember">';
                    //$content .='<input type="hidden" name="action" value="banUser"/>';
                    $content .='<br /><input type="button" id="ban' . $i . '" value="Ban" class="button left tiny" align="center" onclick=\'banUser("' . $row2['uid'] . '");\'></input>'; 
                    $content .='</form>';
                } else if ($row2['groupId'] == 4) {
                    ++$j;
                    $content .='<br /><input type="button" id="unban' . $j . '" value="unBan" class="button left tiny" align="center" onclick=\'unbanUser("' . $row2['uid'] . '");\'></input>';
                }
            }
            
            if($_SESSION['uid']==$row2['uid']){
                //hide send msg to self 
            }else{
                $content .='<br /><a href="privatemessage.php?ruid='.$row2['uid'].'" >Message</a>';
            }
            $content .='</td>';
            $content .='<td width="950px" colspan="2">' . $row2['message'] . '</td>';
            $content .='</tr>';
            $content .='<tr>';
            $content .='<td colspan="2"></td>';
            $content .='<td align="right">';
            if ($_SESSION['uid']==$row2['uid']) {
                $content .='<input type="button" id="modify' . $i . '" value="Modify" class="button left tiny" align="center" onclick=\'displayModifyComment("'.$row2['pid'].'");\'></input>';           
            }
            if($_SESSION['groupId'] == 1 || $_SESSION['groupId'] == 2){
                $content .='<input type="button" id="delete' . $i . '" value="Delete" class="button left tiny" align="center" onclick=\'deletePost("' . $row2['pid'] . '");\'></input>';
            }
            $content .='</td>';
            $content .='</tr>';



                $content .='</table>';
                $content .='<table id="tableEditComment'.$row2['pid'].'" name="tableEditComment'.$row2['pid'].'" align="center" style="table-layout: fixed; width: 65%; display:none">';
                $content .='<tr>';
                $content .='<br />';
                $content .='<td><div><textarea name="commentModify'.$row2['pid'].'" id="commentModify'.$row2['pid'].'" maxLength="500" rows="5" cols="5" style="table-layout: fixed; width: 100%; height: 100%" onblur="validateNonEmptyModifyComment(this,'.$row2['pid'].')">'.$row2['message'].'</textarea></div>';
                $content .='<div class="alert alert-box" data-alert id="commentModify'.$row2['pid'].'Err" style="display: none">Must not be empty</div>';
                $content .='</br ><b id="charcounter'.$row2['pid'].'"/>';
                $content .='</td>';
                $content .='</tr>';
                $content .='<tr>';
                $content .='<td align="right">';
                $content .='<input type="button" id="cancel'.$row2['pid'].'" value="Cancel'.$row2['pid'].'" class="button right small" align="center" onclick=\'hideModifyComment("'.$row2['pid'].'");\'></input>';
                $content .='<input type="button" id="modify'.$row2['pid'].'" value="Modify'.$row2['pid'].'" class="button right small" align="center" onclick=\'modifyPost("'.$row2['pid'].'");\'></input>';
                $content .='</td>';
                $content .='</tr>';
                $content .='</table>';
        }
        $content .='<table align="center" style="table-layout: fixed; width: 65%">';
        $content .='<tr>';
        $content .='<br />';
        $content .='<td><div><textarea placeholder="Enter your comment" name="comment" id="comment"  maxLength="500" rows="5" cols="5" style="table-layout: fixed; width: 100%; height: 100%" onblur="validateNonEmptyComment(this)" "></textarea></div>';
        $content .='<div class="alert alert-box" data-alert id="commentErr" style="display: none">Must not be empty</div>';
        $content .='</br ><b id="charcounter"/>';
        $content .='</td>';
        $content .='</tr>';
        $content .='<tr>';
        $content .='<td align="right">';
        $content .='<input type="button" id="submitNewPost" value="Reply" class="button right small" align="center" onclick=\'addNewPost();\'></input>';
        $content .='</td>';
        $content .='</tr>';

        $content .='</table>';
        $content .='<input type="hidden" id="threadId" name="threadId" value="' . htmlspecialchars($tid) . '"></input>';
        $content .='</form></div>';
        echo $content;
    }

    public function getTotalUser() {
        $totalUser = null;
        $pstmtSelect = $this->con->prepare($this->selectTotalUsers);
        $pstmtSelect->bind_result($totalUser);
        $pstmtSelect->execute();
        if ($pstmtSelect->fetch()) {
            return $totalUser;
        }
        $pstmtSelect->close();
    }

    public function getUserPostCount($uid) {
        $totalPost = null;
        $pstmtSelect = $this->con->prepare($this->selectUserPostCount);
        $pstmtSelect->bind_param('s', $uid);
        $pstmtSelect->bind_result($totalPost);
        $pstmtSelect->execute();

        if ($pstmtSelect->fetch()) {
            return $totalPost;
        }
        $pstmtSelect->close();
    }

    public function refreshPostCount() {
        $totaluser = $this->getTotalUser();

        for ($i = 1; $i <= $totaluser; $i++) {
            $postCount = $this->getUserPostCount($i);
            $pstmtupdate = $this->con->prepare($this->updatePostCount);
            $pstmtupdate->bind_param('si', $postCount, $i);
            $pstmtupdate->execute();
        }
        
        if ($pstmtupdate->affected_rows > 0) {
                return TRUE;
                //echo '<script type="text/javascript">alert("success!");</script>'; 
            } else {
                return FALSE;
                //echo '<script type="text/javascript">alert("failed!");</script>'; 
            }
        $pstmtupdate->close();
    }

    public function getTotalThread($forumsid) {
        $totalThread = null;
        $pstmtSelect = $this->con->prepare($this->selectTotalThread) or die($this->con->error);
//      var_dump($pstmtSelect);
        $pstmtSelect->bind_param('i', $forumsid);
        $pstmtSelect->bind_result($totalThread);
        $pstmtSelect->execute();
        $pstmtSelect->store_result();

        while ($pstmtSelect->fetch()) {
            return $totalThread;
        }
        $pstmtSelect->close();
    }

    public function getTotalPost($forumid) {
        $totalPost = null;
        $pstmtSelect = $this->con->prepare($this->selectTotalPost);
        $pstmtSelect->bind_param('s', $forumid);
        $pstmtSelect->bind_result($totalPost);
        $pstmtSelect->execute();
        $pstmtSelect->store_result();

        while ($pstmtSelect->fetch()) {
            return $totalPost;
        }
        $pstmtSelect->close();
    }

    public function getForumLatestPost($fid) {
        $message = 'NULL_MESSAGE';
        $username = 'NULL_USERNAME';
        //$postTime = 'NULL_POST_TIME';
        $postDateTime = 'NULL_POST_DATE_TIME';
        $pstmtSelect = $this->con->prepare($this->selectForumLatestPost) or die($this->con->error);
        //var_dump($pstmtSelect);
        $pstmtSelect->bind_param('s', $fid);
        $pstmtSelect->bind_result($username, $message, $postDateTime);
        $pstmtSelect->execute();
        $pstmtSelect->store_result();

        while ($pstmtSelect->fetch()) {
            return (string) '<td style="color:blue">' . htmlspecialchars(substr($message, 0, 30)) . '..<br />By ' . htmlspecialchars($username) . '&nbsp;' . htmlspecialchars($postDateTime) . '</td>';
        }
        $pstmtSelect->close();
    }

    public function getThreadStarterUsername($tid) {
        $threadStarter = 'NULL_THREAD_STARTER_USERNAME';

        $pstmtSelect = $this->con->prepare($this->selectThreadStarter);
        $pstmtSelect->bind_param('s', $tid);
        $pstmtSelect->bind_result($threadStarter);
        $pstmtSelect->execute();
        $pstmtSelect->store_result();
        while ($pstmtSelect->fetch()) {
            return (string) '<td style="color:blue;text-align:center">' . htmlspecialchars($threadStarter) . '</td>';
        }
        $pstmtSelect->close();
    }

    public function getTotalThreadPost($tid) {
        $threadTotalPost = 'NULL_THREAD_TOTAL_POST';
        $pstmtSelect = $this->con->prepare($this->selectThreadTotalPost);
        $pstmtSelect->bind_param('s', $tid);
        $pstmtSelect->bind_result($threadTotalPost);
        $pstmtSelect->execute();
        $pstmtSelect->store_result();

        while ($pstmtSelect->fetch()) {
            return $threadTotalPost;
        }
        $pstmtSelect->close();
    }

    public function getThreadLastPostFromPost($tid) {
        $username = 'NULL_USERNAME';
        $pid = 'NULL_POSTID';
        $message = 'NULL_MESSAGE';
        //$postTime = 'NULL_POST_TIME';
        $postDateTime = 'NULL_POST_DATE_TIME';

        $pstmtSelect = $this->con->prepare($this->selectThreadLatestPost) or die($this->con->error);
        $pstmtSelect->bind_param('s', $tid);
        $pstmtSelect->bind_result($username, $pid, $message, $postDateTime);
        $pstmtSelect->execute();
        $pstmtSelect->store_result();

        if ($pstmtSelect->fetch()) {
            return (string) '<td style="color:blue"><a href="view_threads.php?permalink=' . htmlspecialchars($tid) . '">' . htmlspecialchars(substr($message, 0, 30)) . '..<br />By ' . htmlspecialchars($username) . '&nbsp;' . htmlspecialchars($postDateTime) . '</a></td>';
        } else {
            return '<td></td>';
        }
        $pstmtSelect->close();
    }

    public function getThreadLastPostFromThread($tid) {
        $username = 'NULL_USERNAME';
        $pid = 'NULL_POSTID';
        $message = 'NULL_MESSAGE';
        //$postTime = 'NULL_POST_TIME';
        $postDateTime = 'NULL_POST_DATE_TIME';

        $pstmtSelect = $this->con->prepare($this->selectThreadLatestPostFromThread) or die($this->con->error);
        $pstmtSelect->bind_param('s', $tid);
        $pstmtSelect->bind_result($username, $pid, $message, $postDateTime);
        $pstmtSelect->execute();
        $pstmtSelect->store_result();

        if ($pstmtSelect->fetch()) {
            return (string) '<td style="color:blue"><a href="view_threads.php?permalink=' . htmlspecialchars($tid) . '">' . htmlspecialchars(substr($message, 0, 30)) . '..<br />By ' . htmlspecialchars($username) . '&nbsp;' . htmlspecialchars($postDateTime) . '</a></td>';
        } else {
            return '<td></td>';
        }
        $pstmtSelect->close();
    }

    public function getUserJoinedDate($uid) {
        $userJoinedDate = 'NULL_USER_JOINED_DATE';

        $pstmtSelect = $this->con->prepare($this->selectUserJoinedDate);

        $pstmtSelect->bind_param('s', $uid);
        $pstmtSelect->bind_result($userJoinedDate);
        $pstmtSelect->execute();
        $pstmtSelect->store_result();

        while ($pstmtSelect->fetch()) {
            return (string) '<td>Joined Date :' . htmlspecialchars($userJoinedDate) . '</td>';
            //(string)'<td>Joined Date :'.htmlspecialchars($userJoinedDate).'</td>';
        }
        $pstmtSelect->close();
    }

    public function getNewPostID() {
        $postID = NULL;
        $pstmtSelect = $this->con->prepare($this->selectNextPostId);
        $pstmtSelect->bind_result($postID);
        $pstmtSelect->execute();
        $pstmtSelect->store_result();

        if ($pstmtSelect->fetch()) {
            return $postID + 1;
        }
    }

    public function getNewPostID2() {
        $pstmtSelect = $this->con->prepare($this->selectCountPostId);
        $pstmtSelect->bind_result($postID);
        $pstmtSelect->execute();
        $pstmtSelect->store_result();

        if ($pstmtSelect->fetch()) {
            return $postID + 1;
        }
        $pstmtSelect->close();
    }

    public function insertPost($threadID, $userID, $message) {
        $postID = $this->getNewPostID2();
        $title = NULL;
        $status = 'Available';
        $postTime = $this->getTimeNow();
        $postDate = date("Y-m-d");
        try {
            $pstmtInsert = $this->con->prepare($this->insertPost);
            $pstmtInsert->bind_param('iiisssss', $postID, $threadID, $userID, $title, $message, $postDate, $postTime, $status);
            $pstmtInsert->execute();
            $pstmtInsert->store_result();

            if ($pstmtInsert->affected_rows > 0) {
                return TRUE;
            } else {
                return FALSE;
            }
        } catch (PDOException $e) {
            echo $e->getMessage();
        }
        $pstmtInsert->close();
    }

    public function getTimeNow() {
        $nowTime = new DateTime();
        $nowTime->setTimezone(new DateTimeZone('Asia/Kuala_Lumpur'));
        return $nowTime->format('H:i:s');
    }

    public function getNewThreadID() {
        $threadID = NULL;
        $pstmtSelect = $this->con->prepare($this->selectNextThreadId);
        $pstmtSelect->bind_result($threadID);
        $pstmtSelect->execute();
        $pstmtSelect->store_result();

        if ($pstmtSelect->fetch()) {
            return $threadID + 1;
        }
        $pstmtSelect->close();
    }
    
    public function getNewThreadID2() {
        $threadID = NULL;
        $pstmtSelect = $this->con->prepare($this->selectThreadCountId);
        $pstmtSelect->bind_result($threadID);
        $pstmtSelect->execute();
        $pstmtSelect->store_result();

        if ($pstmtSelect->fetch()) {
            return $threadID + 1;
        }
        $pstmtSelect->close();
    }
    
    

    public function createThread($forumID, $userID, $title, $message) {
        $threadID = $this->getNewThreadID2();
        $threadTime = $this->getTimeNow();
        $threadDate = date("Y-m-d");
        try {
            $pstmtInsert = $this->con->prepare($this->insertThread);
            $pstmtInsert->bind_param('iiissss', $threadID, $forumID, $userID, $title, $message, $threadDate, $threadTime);
            $pstmtInsert->execute();
            $pstmtInsert->store_result();

            if ($pstmtInsert->affected_rows > 0) {
                return TRUE;
            } else {
                return FALSE;
            }
        } catch (PDOException $e) {
            echo $e->getMessage();
        }
    }

    public function getForumCategoryTitle($fid) {
        $forumtitle = NULL;
        $pstmtSelect = $this->con->prepare($this->selectForumTitle);
        $pstmtSelect->bind_param('s', $fid);
        $pstmtSelect->bind_result($forumtitle);
        $pstmtSelect->execute();
        $pstmtSelect->store_result();

        if ($pstmtSelect->fetch()) {
            return $forumtitle;
        } else {
            return 'INVALID_ERROR_CAUSED';
        }
    }

    public function getCurrentForumPagePath($fid) {
        if ($fid == 1) {
            echo '<a href="ForumMain.php">Forum</a><img src="img/small-arrow.jpg"><a href="view_thread.php?permalink=1">General Discussion</a>';
        } else if ($fid == 2) {
            echo '<a href="ForumMain.php">Forum</a><img src="img/small-arrow.jpg"><a href="view_thread.php?permalink=2">Off Topic</a>';
        } else {
            echo '<a href="ForumMain.php">Forum</a><img src="img/small-arrow.jpg"><a href="view_thread.php?permalink=3"><u>Technical Problem</u></a>';
        }
    }

    public function getForumThreadTitle($tid) {
        $forumtitle = NULL;
        $pstmtSelect = $this->con->prepare($this->selectThreadTitleOnly);
        $pstmtSelect->bind_param('s', $tid);
        $pstmtSelect->bind_result($threadtitle);
        $pstmtSelect->execute();
        $pstmtSelect->store_result();

        if ($pstmtSelect->fetch()) {
            return $threadtitle;
        } else {
            return 'INVALID_ERROR_CAUSED';
        }
    }

    public function getCurrentThreadPagePath($tid) {
        $pstmtSelect = $this->con->prepare($this->selectThreadTitle);
        $pstmtSelect->bind_param('s', $tid);
        $pstmtSelect->bind_result($forumTitle, $fid, $threadTitle);
        $pstmtSelect->execute();
        $pstmtSelect->store_result();

        if ($pstmtSelect->fetch()) {
            echo '<a href="ForumMain.php">Forum</a><img src="img/small-arrow.jpg">
                  <a href="view_thread.php?permalink=' . htmlspecialchars($fid) . '">' . htmlspecialchars($forumTitle) . '</a>
                  <img src="img/small-arrow.jpg"><a href="#">' . htmlspecialchars($threadTitle) . '</a>';
        } else {
            
        }
    }

    public function checkUserPostStatus($uid) {
        $pstmtSelect = $this->con->prepare($this->selectUserGrpId);
        $pstmtSelect->bind_param('s', $uid);
        $pstmtSelect->bind_result($grpId);
        $pstmtSelect->execute();
        $pstmtSelect->store_result();

        if ($pstmtSelect->fetch()) {
            if ($grpId == 1 || $grpId == 2 || $grpId == 3) {
                return TRUE;
            }
            else
            //unable to post
                return FALSE;
        }else {
            //unable to post
            return FALSE;
        }
    }
    
    public function deletePost($pid){
        $pstmtUpdate = $this->con->prepare($this->deletePost);
        $pstmtUpdate->bind_param('s', $pid);
        $pstmtUpdate->execute();
        
        if($pstmtUpdate->affected_rows > 0){
            return TRUE;
        }else{
            return FALSE;
        }
    }
    
    
    public function banUser($uid){
        $pstmtUpdate = $this->con->prepare($this->updateBanUser);
        $pstmtUpdate->bind_param('s', $uid);
        $pstmtUpdate->execute();
        
        if($pstmtUpdate->affected_rows > 0){
            return TRUE;
        }else{
            return FALSE;
        }
    }
    
    public function unBanUser($uid){
        $pstmtUpdate = $this->con->prepare($this->updateUnBanUser);
        $pstmtUpdate->bind_param('s', $uid);
        $pstmtUpdate->execute();
        
        if($pstmtUpdate->affected_rows > 0){
            return TRUE;
        }else{
            return FALSE;
        }
    }
    
    public function modifyPost($pid,$message){
        $pstmtUpdate = $this->con->prepare($this->updatePost);
        $pstmtUpdate->bind_param('ss', $message, $pid);
        $pstmtUpdate->execute();
        
        if($pstmtUpdate->affected_rows >0){
            return TRUE;
        }else{
            return FALSE;
        }
    }

    public function displayCreateThread(){
        $content = '';
        
        $content .='<div class="row">';
        $content .='<fieldset>';
        $content .='<legend>'.$this->getForumCategoryTitle($_REQUEST['threads']).'</legend>';
        $content .='<legend style="font-size:100%;">&nbsp;&nbsp;Post New Thread</legend><hr />';
        $content .='<form id="newthreadform">';
        $content .='<input type="hidden" name="action" value="addNewThread"/>';
        $content .='<input type="hidden" id="forumId" name="forumId" value="'.htmlspecialchars($_REQUEST['threads']).'"/>';
        $content .='<table width="80%" align="center">';
        $content .='<tr><td>';
        $content .='<div ><label for="title" >Title</label></div>';
        $content .='</td>';
        $content .='</tr>';
        $content .='<tr><td>';
        $content .='<div><input id="title" name="title" type="text" placeholder="Enter a new title" onblur="validateNonEmptyComment(this)"/></div>';
        $content .='<div class="alert alert-box" data-alert id="titleErr" style="display: none">Must not be empty</div>';
        $content .='</td></tr>';
        $content .='<tr><td><label id="lblComment">Comment<label></td></tr>';
        $content .='<tr><td><div><textarea placeholder="Enter your comment" name="comment" id="comment" maxLength="500" rows="5" cols="5" style="table-layout: fixed; width: 100%; height: 100%" onblur="validateNonEmptyComment(this)"></textarea></div>';
        $content .='<div class="alert alert-box" data-alert id="commentErr" style="display: none">Must not be empty</div>';
        $content .='</br ><b id="charcounter"/>';
        $content .='</td></tr>';
        $content .='<tr>';
        $content .='<td>';
        $content .='<br /><input type="button" id="back" value="Back" class="button right huge" align="center"></input></div>';
        $content .='<input type="button" id="submit" value="Submit New Thread" class="button right huge" align="center" onclick=\'addNewThread();\'></input></div>';    
        $content .='</td>';
        $content .='</tr>';
        $content .='</table>';
        $content .='</form>';
        $content .='</fieldset>';
        $content .='</div>';
        echo $content;
    }
}

?>
